import { defineStore } from "pinia";
import { RouteRecordRaw } from "vue-router";
import { GeneraDataType } from "@/interface";
// import { asyncRoutes } from "@/router/data";
import { BaseRouteList } from "@/router/baseRoute";
import store from "../index";
import { clearAuthent, getAuthent, setAuthent } from "@/utils/auth";
import { getUserInfoApi } from "@/api/login/index";
import { message } from "ant-design-vue";
import CommonHook from "@/hook/commonHook";
import { getUserCustomConfigApi } from "@/api/common";
// useStore 可以是 useUser、useCart 之类的任何东西
// 第一个参数是应用程序中 store 的唯一 id
interface PermissionStore {
  baseRoutes: Array<any>;
  asyncRoutes: Array<any>;
  permissionMap: { [propsName: string]: GeneraDataType };
  loadMicroAppMap: { [propsName: string]: GeneraDataType };
  loadedMicroApp: boolean;
  btnAuth: Array<string>;
  whiteList: Array<string>;
  cacheList: Array<string>;
  userInfo: Base.GeneraDataType;
  isReferesh: boolean;
  activePath: string;
  flatteningMenu: Array<Base.GeneraDataType>;
  fieldColumn: Base.GeneraDataType;
}
const { flattening, parse, stringify } = CommonHook();
export const usePermissionStore = defineStore("permission", {
  // other options...
  state: (): PermissionStore => {
    const asyncRoutesCache = JSON.parse(getAuthent("menuList") as string) || [];
    const permissionMapCache = JSON.parse(getAuthent("permissionMap") as string) || {};
    const userInfoCache = JSON.parse(getAuthent("user") as string) || {};
    const flatteningMenuCache = JSON.parse(getAuthent("flatteningMenu") as string) || [];
    const fieldColumnCache = parse(window.localStorage.getItem("fieldColumn") as string) || {};
    const btnAuthCache = JSON.parse(getAuthent("btnAuth") as string) || [];
    return {
      baseRoutes: BaseRouteList, // 基础路由
      asyncRoutes: asyncRoutesCache, // 异步动态路由
      permissionMap: permissionMapCache,
      userInfo: userInfoCache,
      flatteningMenu: flatteningMenuCache,
      fieldColumn: fieldColumnCache,
      btnAuth: btnAuthCache,
      loadMicroAppMap: {},
      activePath: "",
      loadedMicroApp: false,
      isReferesh: false,
      whiteList: ["/401", "/404", "/login", "/outPage/signIn"],
      cacheList: ["MicroAppView"] // 需要keepAlive缓存的组件、此处默认将渲染子应用的组件加入缓存列表、解决子应用跳转回主应用后子应用会被销毁的问题
    };
  },
  actions: {
    // 获取用户信息
    async getUserInfo() {
      return getUserInfoApi().then(async (res: any) => {
        const { code, data } = res;
        if (code === 200) {
          const { menuList, user, tenant, clienType, permissions } = data;
          this.userInfo = user;
          this.userInfo.tenant = tenant;
          // message.success(`欢迎，进入${user.name}Sass系统!`);
          if (!menuList || (menuList && !menuList.length)) {
            message.error("当前用户无菜单，请检查配置!");
            clearAuthent();
            window.location.reload();
            return;
          }
          this.asyncRoutes = this.formattingRouteInfo(menuList || []);
          await this.initPermissionMap(this.asyncRoutes);
          // 按钮
          this.btnAuth = permissions || [];
          setAuthent("btnAuth", JSON.stringify(this.btnAuth));
          this.flatteningMenu = flattening(this.asyncRoutes);
          setAuthent("flatteningMenu", JSON.stringify(this.flatteningMenu));
          setAuthent("menuList", JSON.stringify(this.asyncRoutes));
          setAuthent("user", JSON.stringify(this.userInfo) || "{}");
          setAuthent("permissionMap", JSON.stringify(this.permissionMap));
          setAuthent("clientType", clienType);
          this.isReferesh = true;
        }
      });
    },
    // 设置缓存列表
    async operationCache(mode = "add", val: string) {
      switch (mode) {
        case "add":
          this.cacheList.push(val);
          break;
        case "delete":
          this.cacheList = this.cacheList.filter((t: string) => t !== val);
          break;
        case "keepTarget": // 只保留当前激活的页面缓存
          this.cacheList = this.cacheList.filter((t: string) => ["MicroAppView", val].includes(t));
          break;
        default:
          this.cacheList.push(val);
          break;
      }
    },
    // 清空缓存列表
    async clearCacheList() {
      this.cacheList = ["MicroAppView"];
    },
    // 处理路由层级
    formattingRouteInfo(routeArray: Array<GeneraDataType>) {
      routeArray.forEach(async (t: any) => {
        // 过滤按钮
        if (t.type !== 3) {
          this.activePath = t.path;
          t.meta = {
            icon: t.icon,
            menuName: t.name
          };
          t.menuName = t.name;
          // 后端数据名称与前端路由 name重复、这里转换一下
          t.name = t.component;
          if (t.type === 2) {
            // 菜单
            t.component = {};
          } else if (t.type === 1) {
            // 目录
            t.component = null;
            if (t.child[0]) t.redirect = t.child[0].path;
          }
          if (t.webCache === 1) this.cacheList.push(t.name);
          if (t.child && t.child.length) {
            t.children = this.formattingRouteInfo(t.child).filter((r: any) => r.type !== 3) || [];
            return;
          } else {
            t.children = [];
          }
        }
      });
      return routeArray;
    },
    // 权限初始化
    async initPermissionMap(routeList: Array<RouteRecordRaw>) {
      for (let i = 0; i < routeList.length; i++) {
        const route = routeList[i];
        this.setPagePermission(route.path);
        if (route.children && route.children.length) await this.initPermissionMap(route.children);
      }
    },
    // 设置页面级权限
    async setPagePermission(path: string) {
      if (this.permissionMap[path]) return;
      this.permissionMap[path] = {
        btnAuth: [], // 按钮权限code 集合
        level: [] // 权限等级、等其他一些维度的权限信息
      };
    },
    // 设置按钮权限
    async setBtnPermission(path: string, code: string) {
      if (!this.permissionMap[path]) return;
      const target = this.permissionMap[path].btnAuth;
      target.push(code);
      this.permissionMap[path].btnAuth = Array.from(new Set(target));
    },
    // 获取个性化配置
    async initCustomConfig() {
      return getUserCustomConfigApi().then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          if (data && data.length) {
            this.fieldColumn = parse(data[0].fieldConfigJson || "{}");
            window.localStorage.setItem("fieldColumn", stringify(this.fieldColumn));
          } else {
            this.fieldColumn = {};
            window.localStorage.setItem("fieldColumn", stringify(this.fieldColumn));
          }
        }
      });
    }
  },
  persist: true
});

export default usePermissionStore(store);
